package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.Setmeal;
import com.itheima.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 体检预约服务
 */
@Service(interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private MemberService memberService;

    //体检预约
    public Result order(Map map) throws Exception {
        /**
         1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
         2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
         3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
         4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
         5、预约成功，更新当日的已预约人数
         */

        //获取日期  判断该日期能否进行预约
        String orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);//根据日期查询预约设置信息
        if (orderSetting == null) {
            //所选日期没有提前进行预约设置，不能完成预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        if (orderSetting.getReservations() >= orderSetting.getNumber()) {
            //所选日期已经约满，无法预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //判断是否在重复预约
        String telephone = (String) map.get("telephone");
        Member member = memberDao.findByTelephone(telephone);
        if (member != null) {
            Integer memberId = member.getId();//会员id
            Integer setmealId = Integer.parseInt((String) map.get("setmealId"));//套餐id
            Order order = new Order(memberId, date, setmealId);
            List<Order> orderList = orderDao.findByCondition(order);
            if (orderList != null && orderList.size() > 0) {
                //用户在重复预约，不能完成预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }

        if (member == null) {
            //当前用户不是会员，需要自动完成注册
            member = new Member();
            member.setName((String) map.get("name"));
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setRegTime(new Date());
            memberDao.add(member);
        }

        //保存预约信息
        Order order = new Order(member.getId(),
                date,
                (String) map.get("orderType"),
                Order.ORDERSTATUS_NO,
                Integer.parseInt((String) map.get("setmealId")), (Integer) map.get("addressId"));
        orderDao.add(order);

        //更新已预约人数
        orderSetting.setReservations(orderSetting.getReservations() + 1);
        orderSettingDao.editReservationsByOrderDate(orderSetting);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    //根据id查询预约详细信息（包括会员姓名、套餐名称、预约基本信息）
    public Map findById(Integer id) {
        Map map = orderDao.findById4Detail(id);
        if (map != null) {
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            try {
                map.put("orderDate", DateUtils.parseDate2String(orderDate));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    //    预约订单管理的分页查询
    @Override
    public PageResult findPageByOrder(QueryPageBean queryPageBean) throws Exception {
//        获取所有的条件
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        List<Date> findOrderDate = queryPageBean.getFindOrderDate();
        String findOrderType = queryPageBean.getFindOrderType();
        String findOrderStatus = queryPageBean.getFindOrderStatus();
//        根据日期查询的开始日期和结束日期分别定义
        Date OrderDateBegin = null;
        Date OrderDateEnd = null;
        if (findOrderDate != null && findOrderDate.size() > 0) { //判断是否有日期条件
            OrderDateBegin = findOrderDate.get(0);
            OrderDateEnd = findOrderDate.get(1);
        }
//        创建一个map集合接收所有查询条件
        Map<String, Object> map = new HashMap<>();
        map.put("queryString", queryString);
        map.put("OrderDateBegin", OrderDateBegin);
        map.put("OrderDateEnd", OrderDateEnd);
        if ("1".equals(findOrderStatus)) {
            map.put("findOrderStatus", "未到诊");
        } else if ("2".equals(findOrderStatus)) {
            map.put("findOrderStatus", "已到诊");
        }
        if ("1".equals(findOrderType)) {
            map.put("findOrderType", "微信预约");
        } else if ("2".equals(findOrderType)) {
            map.put("findOrderType", "电话预约");
        }
        PageHelper.startPage(currentPage, pageSize);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");// 指定格式化格式

        //根据会员名或者手机号查询预约信息
        if (queryString != null && queryString.length() > 0) {
            Member member = memberDao.findMemberByCondition(queryString);//查询会员表
            Integer memberId = member.getId();//获取会员id
            Page<Order> page = orderDao.findOrderDataByMemberId(memberId);//通过会员id查询预约表
            for (Order order : page) {
                Integer setmealId = order.getSetmealId(); //获取套餐id
                order.setSetmeal(setmealDao.findById4Detail(setmealId)); //根据套餐id查询套餐信息
                order.setMember(member);
//                设置日期格式
            }
            return new PageResult(page.getTotal(), page.getResult());
        } else {  //只根据预约表字段作为查询条件
            Page<Order> page = orderDao.findOrderPage(map);
            for (Order order : page) {
                Integer memberId = order.getMemberId(); //获取会员id
                order.setMember(memberDao.findById(memberId)); //根据会员id查询会员信息
                Integer setmealId = order.getSetmealId(); //获取套餐id
                order.setSetmeal(setmealDao.findById4Detail(setmealId)); //根据套餐id查询套餐信息
            }
            return new PageResult(page.getTotal(), page.getResult());
        }
    }

    //删除预约信息
    @Override
    public void delete(Integer id) {
        orderDao.deleteByOrder(id);
    }

    //查询套餐表的所有套餐信息
    @Override
    public List<Setmeal> findAllSetmeal() {
        return setmealDao.findAll();
    }


    @Override
    public Result add(Map map, Integer[] setmealIds) throws Exception {

        //获取日期  判断该日期能否进行预约
        Date orderDate = DateUtils.parseString2Date((String) map.get("orderDate"));
        String stringDate = DateUtils.parseDate2String(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(orderDate);//根据日期查询预约设置信息
        if (orderSetting == null) {
            //所选日期没有提前进行预约设置，不能完成预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }

        if (orderSetting.getReservations() >= orderSetting.getNumber()) {
            //所选日期已经约满，无法预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        //判断是否在重复预约 根据手机号查询会员信息
        String phoneNumber = (String) map.get("phoneNumber");
        Member member = memberDao.findByTelephone(phoneNumber);

        if (member != null) {  //会员信息可以查询到  判断是否已经预约
            for (Integer setmealId1 : setmealIds) {
                Integer memberId1 = member.getId();//会员id
                Order order = new Order(memberId1, orderDate, setmealId1);
                List<Order> orderList = orderDao.findByCondition(order);
                if (orderList != null && orderList.size() > 0) {
                    //用户在重复预约，不能完成预约
                    return new Result(false, MessageConstant.HAS_ORDERED);
                }
            }
        }


        //        根据该手机号没有查询到会员信息
        if (member == null) {    //自动会员注册
            member = new Member();
            member.setPhoneNumber(phoneNumber);
            member.setRegTime(new Date());
            member.setName((String) map.get("name"));
            member.setSex((String) map.get("sex"));
            member.setRemark((String) map.get("remark"));
            memberService.add(member);
        }

        Integer memberId = member.getId();
        if (setmealIds != null && setmealIds.length > 0) {

            for (Integer setmealId : setmealIds) {//检查项id
                Map<String, Object> map1 = new HashMap<>();
                map1.put("memberId", memberId);
                map1.put("orderType", Order.ORDERTYPE_TELEPHONE);
                map1.put("orderStatus", Order.ORDERSTATUS_NO);
                map1.put("orderDate", orderDate);
                map1.put("setmealId", setmealId);
                orderDao.setOrderSetmeal(map1);
                //更新已预约人数
                orderSetting.setReservations(orderSetting.getReservations() + 1);
                orderSettingDao.editReservationsByOrderDate(orderSetting);
            }
        }
        return new Result(true, MessageConstant.ORDER_SUCCESS);

    }

    @Override
    public Order findEditDataById(Integer id) {
        return orderDao.findEditDataById(id);
    }

    public Map findCountByDate(List<String> list) {
        List<Integer> orderCount = new ArrayList<>();
        List<Integer> visitCount = new ArrayList<>();
        for (String date : list) {
            Integer orderCountByDate = orderDao.findOrderCountByDate(date);
            Integer visitsCountByDate = orderDao.findVisitsCountByDate(date);
            orderCount.add(orderCountByDate);
            visitCount.add(visitsCountByDate);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("orderCount", orderCount);
        map.put("visitCount", visitCount);
        map.put("everyDay", list);
        return map;
    }

    @Override
    public List<Map> getOrderInfoByMemberIdAndDate(Map map) {
        return orderDao.getOrderInfoByMemberIdAndDate(map);
    }

    @Override
    public Map findOrderDetailsByOrderId(Integer orderId) {
        return orderDao.findOrderDetailsByOrderId(orderId);
    }



    //根据预约id查询套餐id
    @Override
    public Integer findSetmealIdByOrderId(Integer id) {
        return orderDao.findSetmealIdByOrderId(id);
    }

    //编辑
    @Override
    public void edit(Order order) {
        try {
            //基本信息修改
            if ("1".equals(order.getOrderStatus())) {
                order.setOrderStatus("未到诊");
            } else if ("2".equals(order.getOrderStatus())) {
                order.setOrderStatus("已到诊");
            }
            if ("1".equals(order.getOrderType())) {
                order.setOrderType("微信预约");
            } else if ("2".equals(order.getOrderType())) {
                order.setOrderType("电话预约");
            }
            orderDao.edit(order);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //开关按钮更新操作
    @Override
    public void updateStatusAndtype(Order order) {
        orderDao.edit(order);
    }

    @Override
    public Map getOrderInfoByMemberId(Integer id) {
        return null;
    }
}
